package host.skiree.nettydemo.server.dto.impl;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import host.skiree.nettydemo.server.dto.RoomChannel;
import io.netty.channel.Channel;

import java.util.*;

/**
 * @author gcl
 * @date 2022/9/20 9:00
 */
public class RoomChannelImpl implements RoomChannel {

    /**
     * 用于存储 房间名和用户名集合 的对应关系 HashBiMap 线程不安全
     */
    public static HashMap<String, Set<String>> ROOM_CHANNEL_MAP = new HashMap<>();

    @Override
    public HashMap<String, Set<String>> createGroup(String name, Set<String> members) {
        System.out.println(ROOM_CHANNEL_MAP);
        if ( ROOM_CHANNEL_MAP.get(name) == null ){
            ROOM_CHANNEL_MAP.putIfAbsent(name, members);
            System.out.println(ROOM_CHANNEL_MAP);
            return ROOM_CHANNEL_MAP;
        }
        return null;
    }

    @Override
    public HashMap<String, Set<String>> joinMember(String name, String member) {
        if ( ROOM_CHANNEL_MAP.get(name) != null ){
            Objects.requireNonNull(ROOM_CHANNEL_MAP.get(name)).add(member);
            return ROOM_CHANNEL_MAP;
        }
        return null;
    }

    @Override
    public HashMap<String, Set<String>> removeMember(String name, String member) {
        if ( ROOM_CHANNEL_MAP.get(name) != null ){
            Objects.requireNonNull(ROOM_CHANNEL_MAP.get(name)).remove(member);
            return ROOM_CHANNEL_MAP;
        }
        return null;
    }

    @Override
    public HashMap<String, Set<String>> removeGroup(String name) {
        if ( ROOM_CHANNEL_MAP.get(name) != null ){
            Objects.requireNonNull(ROOM_CHANNEL_MAP.remove(name));
            return ROOM_CHANNEL_MAP;
        }
        return null;
    }

    @Override
    public Set<String> getMembers(String name) {
        if ( ROOM_CHANNEL_MAP.get(name) != null ){
            return ROOM_CHANNEL_MAP.get(name);
        }
        return null;
    }

    @Override
    public List<Channel> getMembersChannel(String name) {
        if ( ROOM_CHANNEL_MAP.get(name) != null ){
            if (!UserChannelImpl.USER_CHANNEL_MAP.isEmpty()){
                Set<String> names = ROOM_CHANNEL_MAP.get(name);
                List<Channel> channels = new ArrayList<>();
                UserChannelImpl.USER_CHANNEL_MAP.forEach((key, value) -> {
                    if ( names.contains(value) ){
                        channels.add(key);
                    }
                });
                return channels;
            }
        }
        return null;
    }

}
